package com.shenyue.nbtownlet.ui;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.databinding.ToggleButtonViewBinding;

public class ToggleToolbar extends Toolbar implements RadioGroup.OnCheckedChangeListener {
    private ToggleButtonViewBinding binding;
    private View view;

    public interface OnButtonCheckedChangeListener {
        void onCheckedChanged(int i);
    }

    private OnButtonCheckedChangeListener mOnButtonCheckedChangeListener;

    public ToggleToolbar(Context context) {
        this(context, null);
    }

    public ToggleToolbar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.toolbarStyle);
    }

    public ToggleToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.toggle_button_view, null, false);
        binding.segmented.setOnCheckedChangeListener(this);
        view = binding.getRoot();
        addView(view, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        view.setX((getWidth() - view.getWidth()) / 2);
    }

    @Override
    public void setTitle(CharSequence title) {
    }

    public void addButton(String s) {
        RadioButton radioButton = (RadioButton) LayoutInflater.from(getContext()).inflate(R.layout.radio_button_item, this, false);
        radioButton.setText(s);
        binding.segmented.addView(radioButton);
        binding.segmented.updateBackground();
    }

    public void setChecked(int i) {
        binding.segmented.check(binding.segmented.getChildAt(i).getId());
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        int len = group.getChildCount();
        for (int i = 0; i < len; i++) {
            if (group.getChildAt(i).getId() == checkedId) {
                if (mOnButtonCheckedChangeListener != null)
                    mOnButtonCheckedChangeListener.onCheckedChanged(i);
                break;
            }
        }
    }

    public void setOnButtonCheckedChangeListener(OnButtonCheckedChangeListener listener) {
        mOnButtonCheckedChangeListener = listener;
    }
}